//2+3
import QAstNode from "../model/QAstNode";

const numberReg = /\d/
const code = '2+3'
const tokens1 = code.split('').filter(item => !!item.trim())
console.log(tokens1)

const root = new QAstNode('root')

tokens1.forEach((token, index) => {
    const ast = parserPlus(root, token, token[index + 1] || null)
    root.child.push(ast)
})

function parserPlus(root, cur, next) {
    let ast = null
    if (numberReg.test(cur)) {
        //加法里面要完善代码，要把 a+b这种情况都写进去，用3个token
        if (next === '+') {
            ast = this.parserPlus(root, cur, next)
        } else {
            ast = this.parserNumber(root, cur)
        }
    }
    return ast
}

function parserNumber(ast, cur) {
    if (numberReg.test(cur)) {
        return new QAstNode(cur)
    }
    return null
}









private SimpleASTNode additive(TokenReader tokens) throws Exception {
    SimpleASTNode child1 = multiplicative();  //计算第一个子节点
    SimpleASTNode node = child1;  //如果没有第二个子节点，就返回这个
    Token token = tokens.peek();
    if (child1 != null && token != null) {
        if (token.getType() == TokenType.Plus) {
            token = tokens.read();
            SimpleASTNode child2 = additive(); //递归地解析第二个节点
            if (child2 != null) {
                node = new SimpleASTNode(ASTNodeType.AdditiveExp, token.getText());
                node.addChild(child1);
                node.addChild(child2);
            } else {
                throw new Exception("invalid additive expression, expecting the right part.");
            }
        }
    }
    return node;
}
